// 设置日志对象类的通用属性
function setCommonProperty2() {
    this.happenTime = new Date().getTime(); // 日志发生时间
    this.simpleUrl = window.location.href.split("?")[0].replace("#", ""); // 页面的url
    this.completeUrl = window.location.hrefl; // utils.b64EncodeUnicode(encodeURIComponent(window.location.href)); // 页面的完整url
}
// 接口请求日志，继承于日志基类MonitorBaseInfo
function HttpLogInfo() {
    setCommonProperty2.apply(this);

    this.handleLogInfo = function (logMsg) {
        delete this.handleLogInfo;

        var data = {
            ...getCommonProperty(),
            uploadType: "HTTP_LOG",
            logMsg: logMsg,
        }
        //nginx日志
        new Image().src = "http://log.besteasylearn.com/log.gif?appKey=123&json=" + JSON.stringify(data)

        var res = $.post({
            url: "/log/up_http",
            data: data,
            async: false,
        });
    };
}

/**
 * 页面接口请求监控
 */
function recordHttpLog() {
    // 监听ajax的状态
    function ajaxEventTrigger(event) {
        var ajaxEvent = new CustomEvent(event, { detail: this });
        window.dispatchEvent(ajaxEvent);
    }
    var XMLHttpRequest = window.XMLHttpRequest;
    function newXHR() {
        var realXHR = new XMLHttpRequest();
        realXHR.addEventListener(
            "loadstart",
            function () {
                console.log(this, "ajaxLoadStart")
                ajaxEventTrigger.call(this, "ajaxLoadStart");
            },
            false
        );
        realXHR.addEventListener(
            "loadend",
            function () {
                console.log(this, "ajaxLoadEnd")

                if (this.responseURL.indexOf('log') == -1) {
                    ajaxEventTrigger.call(this, "ajaxLoadEnd");
                }


            },
            false
        );
        // 此处的捕获的异常会连日志接口也一起捕获，如果日志上报接口异常了，就会导致死循环了。
        // realXHR.onerror = function () {
        //   siftAndMakeUpMessage("Uncaught FetchError: Failed to ajax", WEB_LOCATION, 0, 0, {});
        // }
        return realXHR;
    }
    function handleHttpResult(i, tempResponseText) {
        if (!timeRecordArray[i] || timeRecordArray[i].uploadFlag === true) {
            return;
        }
        var responseText = "";
        try {
            responseText = tempResponseText
                ? JSON.stringify(utils.encryptObj(JSON.parse(tempResponseText)))
                : "";
        } catch (e) {
            responseText = "";
        }
        var simpleUrl = timeRecordArray[i].simpleUrl;
        var currentTime = new Date().getTime();
        var url = timeRecordArray[i].event.detail.responseURL;
        var status = timeRecordArray[i].event.detail.status;
        var statusText = timeRecordArray[i].event.detail.statusText;
        var loadTime = currentTime - timeRecordArray[i].timeStamp;
        console.log(url, "end里的url");
        if (!url || url.indexOf("up_http") != -1) {
            console.log("进来了end")
            return;
        };
        var httpLogInfoStart = new HttpLogInfo();
        httpLogInfoStart.handleLogInfo({
            simpleUrl,
            url,
            reqType: "发起请求",
            status,
            statusText,
            timeStamp: timeRecordArray[i].timeStamp,
        });
        var httpLogInfoEnd = new HttpLogInfo(

        );
        httpLogInfoEnd.handleLogInfo({
            simpleUrl,
            url,
            reqType: "请求返回",
            status,
            statusText,
            timeStamp: timeRecordArray[i].timeStamp,
            responseText,
            currentTime,
            loadTime
        });
        // 当前请求成功后就，就将该对象的uploadFlag设置为true, 代表已经上传了
        timeRecordArray[i].uploadFlag = true;
    }

    var timeRecordArray = [];
    window.XMLHttpRequest = newXHR;
    window.addEventListener("ajaxLoadStart", function (e) {
        var tempObj = {
            timeStamp: new Date().getTime(),
            event: e,
            simpleUrl: window.location.href.split("?")[0].replace("#", ""),
            uploadFlag: false,
        };
        timeRecordArray.push(tempObj);
    });

    window.addEventListener("ajaxLoadEnd", function () {
        for (var i = 0; i < timeRecordArray.length; i++) {
            // uploadFlag == true 代表这个请求已经被上传过了
            if (timeRecordArray[i].uploadFlag === true) continue;
            if (timeRecordArray[i].event.detail.status > 0) {
                var rType = (
                    timeRecordArray[i].event.detail.responseType + ""
                ).toLowerCase();


                if (rType === "blob") {
                    (function (index) {
                        var reader = new FileReader();
                        reader.onload = function () {
                            var responseText = reader.result;//内容就在这里
                            handleHttpResult(index, responseText);
                        }
                        try {
                            reader.readAsText(timeRecordArray[i].event.detail.response, 'utf-8');
                        } catch (e) {
                            handleHttpResult(index, timeRecordArray[i].event.detail.response + "");
                        }
                    })(i);
                } else {
                    var responseText = timeRecordArray[i].event.detail.responseText;
                    console.log(i, responseText, "=========responseText========")
                    console.log(timeRecordArray[i], "==========timeRecordArray[i]===========")
                    handleHttpResult(i, responseText);
                }


            }
        }
    });
}

recordHttpLog();
